using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;

namespace Decav.Gatsb.Web.Controls
{
    /// <summary>
    /// A link that goes to a <see cref="User"/>'s page.
    /// </summary>
    public class GatsbUserLink : HtmlAnchor
    {
        public GatsbUserLink()
        {
        }

        private User _user;

        /// <summary>
        /// Gets or sets the User.
        /// </summary>
        public User User
        {
            get
            {
                if (_user == null && UserId != null)
                    _user = GatsbApplication.Current.GetUser(UserId);

                return _user;
            }
            set
            {
                Guid id = Guid.Empty;
                if (value != null)
                    id = value.Id;

                ViewState["UserId"] = id;
                _user = value;

                SetLink();
            }
        }

        /// <summary>
        /// Gets or sets the format of the persons name when rendered in the link.
        /// </summary>
        public NameFormat NameFormat
        {
            get
            {
                if (ViewState["NameFormat"] == null)
                    return NameFormat.FullName;

                return (NameFormat)ViewState["NameFormat"];
            }
            set
            {
                ViewState["NameFormat"] = value;
            }
        }
	

        /// <summary>
        /// Gets or sets the ID of the User.
        /// </summary>
        public Guid UserId
        {
            get
            {
                if (ViewState["UserId"] == null)
                    return Guid.Empty;

                return (Guid)ViewState["UserId"];
            }
            set
            {
                ViewState["UserId"] = value;
                if (value == Guid.Empty)
                    _user = null;
                else
                    _user = GatsbApplication.Current.GetUser(UserId);

                SetLink();
            }
        }

        private void SetLink()
        {
            if (UserId == Guid.Empty)
            {
                this.Visible = false;
                return;
            }

            this.Visible = true;
            HRef = string.Format("Person.aspx?id={0}", UserId);

            if (NameFormat == NameFormat.FullName)
                InnerText = User.Name.ToString();
            else
                InnerText = User.Name.FirstName;
        }

        protected override void OnPreRender(EventArgs e)
        {
            SetLink();
            base.OnPreRender(e);
        }
    }
}
